package com.damai.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class StringUtil {

    private final static Logger logger = LoggerFactory.getLogger(StringUtil.class);

    /**
     * 判断字符串不为空
     * trim函数作用是移除字符串两端的空白字符
     */
    public static boolean isNotEmpty(String str) {
        return (str != null && !str.isEmpty() && !str.trim().isEmpty() && !"null".equalsIgnoreCase(str.trim())
                && !"undefined".equalsIgnoreCase(str.trim()) && !"NULL".equalsIgnoreCase(str.trim()));

    }

    /**
     * 判断字符串为空
     */
    public static boolean isEmpty(String str) {
        return !StringUtil.isNotEmpty(str);
    }

    //将流转换为字符串
    public static String inputStreamConvertString(InputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = null;
        String result = null;
        try {
            if(inputStream != null) {
                byteArrayOutputStream = new ByteArrayOutputStream();
                int i;
                while((i = inputStream.read()) != -1){
                    byteArrayOutputStream.write(i);
                }
                result = byteArrayOutputStream.toString();;
            }
        } catch (IOException e) {
            throw new RuntimeException("流转换为字符串失败!");
        } finally {
            if(byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e){
                    logger.error("关闭流失败!");
                }
            }
        }
        return result;
    }

    /**
     * 将URL参数转成map
     * URL编码:URL参数中的某些字符(如 =, &, ?, 空格等)在URL中有特殊含义,不能直接出现在参数值中;
     * 为了正确传输这些字符,它们会被编码成%加上两位十六进制数的形式(例如空格会被编码为 %20, =编码为 %3D);
     * 例如:
     * 原始参数:name=John Doe&age=30
     * 编码后:name=John%20Doe&age=30
     * 如果不进行解码,John%20Doe会被错误地解析为John和Doe两个部分,导致数据错误;
     */
    public static Map<String, String> convertQueryStringToMap(String queryString) {
        Map<String, String> resultMap = new HashMap<>(256);
        String[] params = queryString.split("&");
        for (String param : params) {
            String[] keyValue = param.split("=");
            if (keyValue.length == 2) {
                try {
                    String key = java.net.URLDecoder.decode(keyValue[0], "UTF-8");
                    String value = java.net.URLDecoder.decode(keyValue[1], "UTF-8");
                    resultMap.put(key, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return resultMap;
    }
}
